package com.happy.lyrics.formats.hrcs;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Base64;

import com.happy.lyrics.LyricsFileWriter;
import com.happy.lyrics.model.LyricsInfo;
import com.happy.lyrics.model.LyricsLineInfo;
import com.happy.lyrics.model.LyricsTag;
import com.happy.lyrics.model.TranslateLrcLineInfo;
import com.happy.lyrics.utils.StringCompressUtils;

/**
 * hrcs歌词
 * 
 * @author zhangliangming
 * 
 */
public class HrcsLyricsFileWriter extends LyricsFileWriter {

	/**
	 * 歌曲名 字符串
	 */
	private final static String LEGAL_TITLE_PREFIX = "[ti:";
	/**
	 * 歌手名 字符串
	 */
	private final static String LEGAL_ARTIST_PREFIX = "[ar:";
	/**
	 * 时间补偿值 字符串
	 */
	private final static String LEGAL_OFFSET_PREFIX = "[offset:";
	/**
	 * 歌曲长度
	 */
	private final static String LEGAL_TOTAL_PREFIX = "[total:";
	/**
	 * 上传者
	 */
	private final static String LEGAL_BY_PREFIX = "[by:";
	/**
	 * Tag标签
	 */
	private final static String LEGAL_TAG_PREFIX = "haplayer.tag[";

	/**
	 * 歌词 字符串
	 */
	public final static String LEGAL_LYRICS_LINE_PREFIX = "haplayer.lrc";
	/**
	 * 额外歌词
	 */
	private final static String LEGAL_EXTRA_LYRICS_PREFIX = "haplayer.extra.lrc";

	public HrcsLyricsFileWriter() {
	}

	@Override
	public boolean writer(LyricsInfo lyricsIfno, String lyricsFilePath)
			throws Exception {
		try {
			File lyricsFile = new File(lyricsFilePath);
			if (lyricsFile != null) {
				//
				if (!lyricsFile.getParentFile().exists()) {
					lyricsFile.getParentFile().mkdirs();
				}
				// 对字符串运行压缩
				byte[] content = StringCompressUtils.compress(
						parseLyricsInfo(lyricsIfno), getDefaultCharset());
				// 生成歌词文件
				FileOutputStream os = new FileOutputStream(lyricsFile);
				os.write(content);
				os.close();

			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 解析歌词对象类转换为字符串
	 * 
	 * @param lyricsIfno
	 * @return
	 */
	private String parseLyricsInfo(LyricsInfo lyricsIfno) {
		String lyricsCom = "";
		// 先保存所有的标签数据
		Map<String, Object> tags = lyricsIfno.getLyricsTags();
		for (Map.Entry<String, Object> entry : tags.entrySet()) {
			Object val = entry.getValue();
			if (entry.getKey().equals(LyricsTag.TAG_TITLE)) {
				lyricsCom += LEGAL_TITLE_PREFIX;
			} else if (entry.getKey().equals(LyricsTag.TAG_ARTIST)) {
				lyricsCom += LEGAL_ARTIST_PREFIX;
			} else if (entry.getKey().equals(LyricsTag.TAG_OFFSET)) {
				lyricsCom += LEGAL_OFFSET_PREFIX;
			} else if (entry.getKey().equals(LyricsTag.TAG_BY)) {
				lyricsCom += LEGAL_BY_PREFIX;
			} else if (entry.getKey().equals(LyricsTag.TAG_TOTAL)) {
				lyricsCom += LEGAL_TOTAL_PREFIX;
			} else {
				lyricsCom += LEGAL_TAG_PREFIX + entry.getKey() + ":";
			}
			lyricsCom += val + "];\n";
		}

		// 获取额外歌词行（翻译歌词和音译歌词）
		JSONObject extraLyricsObj = new JSONObject();
		JSONArray contentArray = new JSONArray();
		// 判断是否有翻译歌词
		if (lyricsIfno.getTranslateLyricsInfo() != null) {
			List<TranslateLrcLineInfo> translateLrcLineInfos = lyricsIfno
					.getTranslateLyricsInfo().getTranslateLrcLineInfos();
			if (translateLrcLineInfos != null
					&& translateLrcLineInfos.size() > 0) {
				JSONObject lyricsObj = new JSONObject();
				JSONArray lyricContentArray = new JSONArray();
				lyricsObj.put("lyricType", 1);
				for (int i = 0; i < translateLrcLineInfos.size(); i++) {
					JSONArray lyricArray = new JSONArray();
					TranslateLrcLineInfo translateLrcLineInfo = translateLrcLineInfos
							.get(i);
					lyricArray.add(translateLrcLineInfo.getLineLyrics());
					lyricContentArray.add(lyricArray);
				}
				if (lyricContentArray.size() > 0) {
					lyricsObj.put("lyricContent", lyricContentArray);
					contentArray.add(lyricsObj);
				}

			}
		}

		// 判断是否有音译歌词
		if (lyricsIfno.getTransliterationLyricsInfo() != null) {
			List<LyricsLineInfo> lyricsLineInfos = lyricsIfno
					.getTransliterationLyricsInfo()
					.getTransliterationLrcLineInfos();
			if (lyricsLineInfos != null && lyricsLineInfos.size() > 0) {
				JSONObject lyricsObj = new JSONObject();
				JSONArray lyricContentArray = new JSONArray();
				lyricsObj.put("lyricType", 0);
				for (int i = 0; i < lyricsLineInfos.size(); i++) {

					LyricsLineInfo lyricsLineInfo = lyricsLineInfos.get(i);
					String[] lyricsWords = lyricsLineInfo.getLyricsWords();
					JSONArray lyricArray = new JSONArray();
					for (int j = 0; j < lyricsWords.length; j++) {
						lyricArray.add(lyricsWords[j].trim());
					}
					lyricContentArray.add(lyricArray);
				}
				if (lyricContentArray.size() > 0) {
					lyricsObj.put("lyricContent", lyricContentArray);
					contentArray.add(lyricsObj);
				}
			}
		}
		//
		extraLyricsObj.put("content", contentArray);
		// 添加翻译和音译歌词
		lyricsCom += LEGAL_EXTRA_LYRICS_PREFIX
				+ "('"
				+ Base64.encodeBase64String(extraLyricsObj.toString()
						.getBytes()) + "');\n";

		// 每行歌词内容
		TreeMap<Integer, LyricsLineInfo> lyricsLineInfos = lyricsIfno
				.getLyricsLineInfoTreeMap();
		// 将每行歌词，放到有序的map，判断已重复的歌词
		LinkedHashMap<String, List<Integer>> lyricsLineInfoMapResult = new LinkedHashMap<String, List<Integer>>();
		for (int i = 0; i < lyricsLineInfos.size(); i++) {
			LyricsLineInfo lyricsLineInfo = lyricsLineInfos.get(i);
			String saveLineLyrics = getSaveLineLyrics(lyricsLineInfo
					.getLyricsWords());
			List<Integer> indexs = null;
			// 如果已存在该行歌词，则往里面添加歌词行索引
			if (lyricsLineInfoMapResult.containsKey(saveLineLyrics)) {
				indexs = lyricsLineInfoMapResult.get(saveLineLyrics);
			} else {
				indexs = new ArrayList<Integer>();
			}
			indexs.add(i);
			lyricsLineInfoMapResult.put(saveLineLyrics, indexs);
		}
		// 遍历
		for (Map.Entry<String, List<Integer>> entry : lyricsLineInfoMapResult
				.entrySet()) {
			lyricsCom += LEGAL_LYRICS_LINE_PREFIX + "('";
			List<Integer> indexs = entry.getValue();
			// 当前行歌词文本
			String saveLineLyrics = entry.getKey();
			String timeText = "";// 时间标签内容
			String wordsDisIntervalText = "";// 每个歌词时间

			for (int i = 0; i < indexs.size(); i++) {
				int key = indexs.get(i);
				LyricsLineInfo lyricsLineInfo = lyricsLineInfos.get(key);
				// 获取开始时间和结束时间
				timeText += "<" + lyricsLineInfo.getStartTime() + ",";
				timeText += lyricsLineInfo.getEndTime() + ">";

				// 获取每个歌词的时间
				String wordsDisIntervalTextTemp = "";
				int wordsDisInterval[] = lyricsLineInfo.getWordsDisInterval();
				for (int j = 0; j < wordsDisInterval.length; j++) {
					if (j == 0)
						wordsDisIntervalTextTemp += wordsDisInterval[j] + "";
					else
						wordsDisIntervalTextTemp += "," + wordsDisInterval[j]
								+ "";
				}
				// 获取每个歌词时间的文本
				wordsDisIntervalText += "<" + wordsDisIntervalTextTemp + ">";
			}
			lyricsCom += timeText + "'";
			lyricsCom += ",'" + saveLineLyrics + "'";
			lyricsCom += ",'" + wordsDisIntervalText + "');\n";
		}
		return lyricsCom;
	}

	/**
	 * 获取要保存的行歌词内容
	 * 
	 * @param lyricsWords
	 * @return
	 */
	private String getSaveLineLyrics(String[] lyricsWords) {
		String saveLineLyrics = "";
		for (int i = 0; i < lyricsWords.length; i++) {
			saveLineLyrics += "<" + lyricsWords[i] + ">";
		}
		return saveLineLyrics;
	}

	@Override
	public boolean isFileSupported(String ext) {
		return ext.equalsIgnoreCase("hrcs");
	}

	@Override
	public String getSupportFileExt() {
		return "hrcs";
	}

}
